package com.tmt.im.manager.service;

import com.tmt.data.jpa.service.TmtJpaDataService;
import com.tmt.im.jpa.entity.IMFriendApply;
import com.tmt.im.jpa.repository.ChatSessionMemberRepo;
import com.tmt.im.jpa.repository.IMFriendApplyRepo;
import com.tmt.im.manager.controller.vo.ApplyTotalInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.OffsetDateTime;

/**
 * @Description TODO
 * @Author wuyi
 * @Date 2024/8/24 17:42
 * @Version 1.0
 **/
@Service
public class IMFriendApplyService extends TmtJpaDataService<IMFriendApply, Long> {

    private final IMFriendApplyRepo imFriendApplyRepo;

    private final ChatSessionMemberRepo sessionMemberRepo;

    private final int validDays;

    public IMFriendApplyService(IMFriendApplyRepo mainRepo,
                                ChatSessionMemberRepo sessionMemberRepo,
                                @Value("${friend-apply.valid-days:1}")
                                int validDays) {
        super(mainRepo);
        this.imFriendApplyRepo = mainRepo;
        this.sessionMemberRepo = sessionMemberRepo;
        this.validDays = validDays;
    }

    public ApplyTotalInfo countByReviewTimeIsNullAndTargetId(Long targetId) {
        //计算过期时间。
        Timestamp expireTime = Timestamp.from((OffsetDateTime.now().minusDays(validDays)).toInstant());
        int friendApplyCount = 0;
        try {
            friendApplyCount = imFriendApplyRepo.countByReviewTimeIsNullAndFriendIdAndCreateTimeAfter(targetId, expireTime);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        int groupApplyCount = 0;
        try {
            //统计未审核通过的且未过期的群组成员数量。
            groupApplyCount = sessionMemberRepo.countByCheckStatusAndAgreeStatusAndCreateTimeAfter(0, 1, expireTime);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return new ApplyTotalInfo(groupApplyCount, friendApplyCount);
    }
}
